#include "remotegenerator.h"
#include "mainwindow.h"
#include "directoryutilities.h"

RemoteGenerator::RemoteGenerator(MainWindow *mainWindow)
    : QObject(mainWindow),
    m_mainWindow(mainWindow)
{
}

RemoteGenerator::~RemoteGenerator()
{
}

void RemoteGenerator::getPage(QUrl url, QString name, bool waitForFinished)
{
	// Clean the dir, otherwise new files will just pile up at every wget call
	m_outputDir = QDir(QDir::tempPath() + HAG_TEMP_DIR + "\\" + name);
	DirectoryUtilities::cleanDirectory(m_outputDir.absolutePath(), true, m_outputDir.absolutePath());

    qDebug() << "getting" << url << name;

	// Using -nd in wget causes all files to be placed in one directory. This is not optimal,
	// since it will mess files from different domains, but using separate directories would
	// be hard for the generator: we would have to pass information which of the folders is
	// the one where to look for the correct index.html. Now the additional files will be renamed
	// to something like "index.html.1.html", and the site's main file will be index.html.
	// (Hopefully -- if there's index.html and it's not the main file, things won't work.)
	QString wget = "wget.exe -E -H -k -nd -p -P \"" + m_outputDir.absolutePath() + "\" " + url.toString();
    qDebug() << wget;
	QProcess *process = new QProcess(this);
	connect(process, SIGNAL(readyReadStandardError()), this, SLOT(debugProcess()));
	connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(debugProcess()));
	connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
	process->start(wget);
	if (waitForFinished)
	{
		// When using the browser interface, without this we will
		// get connection reset
		process->waitForFinished();
	}
}

void RemoteGenerator::debugProcess()
{
	QProcess *pr = (QProcess*)sender();
	QString value(pr->readAllStandardOutput());
	if (!value.isEmpty())
    {
        qDebug() << value;
		emit message(value);
    }

	value = pr->readAllStandardError();
    if (!value.isEmpty())
    {
		emit message(value);
        qDebug() << value;
    }
}

void RemoteGenerator::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
	qDebug() << "Finished with code" << exitCode << ", status" << exitStatus;
	m_mainWindow->setActivePath(m_outputDir.canonicalPath());
	qDebug() << "Disconnecting all debug message listeners";
	disconnect(this, SIGNAL(message(QString)), 0, 0);
	emit finished();
}
